package org.jflame.auth.authc;

import org.jflame.commons.crypto.digest.DigestAlg;
import org.jflame.commons.crypto.digest.DigestHelper;

import java.security.DigestException;
import java.util.regex.Pattern;

import org.apache.commons.lang3.exception.ExceptionUtils;

public class PasswordService {

    private DigestAlg digestAlgorithm;
    /**
     * 强密码规则:至少8位,含大小写字母、数字和特殊符号
     */
    public static final Pattern ROBUSTNESS_REGEX = Pattern.compile("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[\\S]{8,}$");

    public PasswordService() {
        digestAlgorithm = DigestAlg.SHA256;
    }

    public PasswordService(DigestAlg digestAlgorithm) {
        this.digestAlgorithm = digestAlgorithm;
    }

    /**
     * 计算密码消息摘要hash值
     * 
     * @param password 密码
     * @param salt 盐
     * @return
     */
    public String hashPassword(String password, String salt) {
        try {
            return DigestHelper.digestHex(digestAlgorithm, password + "&" + salt);
        } catch (DigestException e) {
            return ExceptionUtils.rethrow(e);
        }
    }

    /**
     * 验证密码是否相同
     * 
     * @param pwdCiphertext 正确的密码密文
     * @param password 输入的密码明文
     * @param salt 盐
     * @return
     */
    public boolean isMatchPassword(String pwdCiphertext, String password, String salt) {
        String pwd = hashPassword(password, salt);
        return pwd.equalsIgnoreCase(pwdCiphertext);
    }

    /**
     * 判断是否是个高强度密码
     * 
     * @param password 密码
     * @return 符合高强度规则返回true
     */
    public boolean isRobustnessPassword(String password) {
        return ROBUSTNESS_REGEX.matcher(password)
                .find();
    }
}
